package com.shey.imageloader.bean;

import android.graphics.Bitmap;
import android.util.LruCache;

import com.shey.imageloader.impl.IBitmapCache;

/**
 * Created by SheyChen on 2015/12/2 15:04.
 * Email 1768037936@qq.com
 * 内存缓存
 */
public class MemoryCache implements IBitmapCache {

    private LruCache<String,Bitmap> mMemoryCache;

    public MemoryCache() {

        final int maxMemorySize = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemorySize / 4;

        mMemoryCache = new LruCache<String,Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                // 重写此方法来衡量每张图片的大小，默认返回图片数量
                return value.getRowBytes() * value.getHeight() / 1024;
            }
        };
    }

    @Override
    public Bitmap get(BitmapRequest bitmapRequest) {
        return mMemoryCache.get(bitmapRequest.imageUri);
    }

    @Override
    public void put(BitmapRequest bitmapRequest, Bitmap bitmap) {
        if (bitmapRequest != null && bitmap != null) {
            mMemoryCache.put(bitmapRequest.imageUri, bitmap);
        }
    }

    @Override
    public void remove(BitmapRequest bitmapRequest) {
        if (bitmapRequest != null) {
            mMemoryCache.remove(bitmapRequest.imageUri);
        }
    }
}
